package com.example.springboot.controller;

import com.example.springboot.dto.*;
import com.example.springboot.entity.Order;
import com.example.springboot.service.OrderService;
import com.example.springboot.service.PaymentService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import com.example.springboot.service.DeviceService;

import java.math.BigDecimal;
import java.util.List;
import java.util.UUID;

@RestController
@Api(tags = "订单管理")
@RequestMapping("/api/orders")
public class OrderController {

    @Autowired
    private OrderService orderService;
    @Autowired
    private DeviceService deviceService;
    @Autowired
    private PaymentService paymentService;

    @ApiOperation(value = "获取所有套餐和自定义选项")
    @GetMapping("/options")
    public OptionResponse getAllOptions() {
        return orderService.getAllOptions();
    }

    @ApiOperation(value = "自助点创建订单", notes = "自助点创建订单")
    @PostMapping("/self-service/create")
    public ResponseEntity<?> selectOrder(@RequestBody OrderRequest request) {
        if (request.getUserId() == null) {
            return ResponseEntity.badRequest().body("用户ID不能为空");
        }
        if (request.getPaymentMethod() == null || request.getPaymentMethod().isEmpty()) {
            return ResponseEntity.badRequest().body("支付方式不能为空");
        }
        try {
            // 创建订单
            Order order = orderService.createOrderAndPayment(request);

            // 创建支付记录（状态为 pending）
            PaymentDTO paymentDTO = new PaymentDTO();
            paymentDTO.setOrderId(order.getOrderId());
            paymentDTO.setUserId(request.getUserId());
            paymentDTO.setOrderType(order.getOrderType()); // 设置订单类型
            paymentDTO.setOrderAmount(order.getOrderAmount());
            paymentDTO.setPaymentMethod(request.getPaymentMethod());
            paymentDTO.setTransactionId("TXN_S_" + order.getOrderId());
            paymentService.createPayment(paymentDTO);

            // 创建响应对象
            OrderResponse orderResponse = new OrderResponse();
            orderResponse.setOrderId(order.getOrderId());
            orderResponse.setUserId(request.getUserId());


            orderResponse.setOrderAmount(order.getOrderAmount().doubleValue());  // 将 BigDecimal 转为 Double

            orderResponse.setPaymentMethod(request.getPaymentMethod());
            orderResponse.setPaymentStatus("pending");  // 假设支付状态是 pending，因为支付尚未完成
            orderResponse.setTransactionId(paymentDTO.getTransactionId());
            orderResponse.setOrderType(order.getOrderType());

            // 返回订单ID和详细信息
            return ResponseEntity.ok(new OrderCreationResponse(
                    "订单和支付记录已创建，请完成支付。",
                    orderResponse
            ));
        } catch (Exception e) {
            return ResponseEntity.status(500).body("创建订单失败: " + e.getMessage());
        }
    }


    @ApiOperation(value = "取衣", notes = "取衣")
    @PostMapping("user/pickup")
    public ResponseEntity<?> pickupOrder(@RequestBody OrderPickupRequest request) {
        if (request.getOrderId() == null || request.getUserId() == null) {
            return ResponseEntity.badRequest().body("订单ID和用户ID不能为空");
        }
        try {
            Order order;

            // 如果 serviceType 为空，使用原逻辑的查询方式
            if (request.getServiceType() == null || request.getServiceType().isEmpty()) {
                // serviceType 为空，查询自助订单
                order = orderService.findSOrderById(request.getOrderId());
            } else {
                // serviceType 不为空，查询商户订单
                order = orderService.findMOrdersById(request.getOrderId());
            }

            if (order == null) {
                return ResponseEntity.badRequest().body("订单未找到");
            }

            String serviceType = order.getServiceType();
            String status = order.getStatus();

            // 处理 rental_pickup_only
            if (serviceType != null && !serviceType.isEmpty() &&
                    ("rental_pickup_only".equals(serviceType) )
                    && "to_be_returned".equals(status)) {

                // 更新状态为 returned
                order.setStatus("returned");
                orderService.updateMerchantOrder(order);
                return ResponseEntity.ok("衣物已归还，（商户订单更新）");
            }

            // 处理 washing_pickup_only
            if (serviceType != null && !serviceType.isEmpty() &&
                        ("washing_pickup_only".equals(serviceType))
                    && "ready_for_pickup".equals(status)) {

                // 更新状态为 completed
                order.setStatus("completed");
                orderService.updateMerchantOrder(order);
                return ResponseEntity.ok("取衣成功，订单已完成（商户订单更新）");
            }

            // 如果 serviceType 为空，或不符合特定类型，继续现有逻辑
            if (!"ready_for_pickup".equals(order.getStatus())) {
                return ResponseEntity.badRequest().body("订单未准备好取衣");
            }

            // 更新订单状态为 completed
            orderService.updateOrderStatusToCompleted(order.getOrderId());

            // 更新设备状态为 available
            deviceService.updateDeviceStatus(order.getDeviceId(), "available");

            return ResponseEntity.ok("取衣成功，订单已完成");
        } catch (Exception e) {
            return ResponseEntity.status(500).body("取衣失败: " + e.getMessage());
        }
    }


    @PostMapping("merchant/pickup")
    public ResponseEntity<?> pickupMOrder(@RequestBody OrderPickupRequest request) {
        if (request.getOrderId() == null || request.getUserId() == null) {
            return ResponseEntity.badRequest().body("订单ID和用户ID不能为空");
        }
        try {
            // 验证订单状态
            Order order = orderService.findMOrdersById(request.getOrderId());
            if (order == null) {
                return ResponseEntity.badRequest().body("订单未找到");
            }
            String serviceType = order.getServiceType();
            String status = order.getStatus();

            if ("washing_pickup_only".equals(serviceType)) {
                switch (status) {
                    case "in_progress":
                        order.setStatus("picked_up");
                        orderService.updateMerchantOrder(order);
                        return ResponseEntity.ok("商家取衣成功"); // 与“点击取衣”对应
                    case "picked_up":
                        order.setStatus("washing");
                        orderService.updateMerchantOrder(order);
                        return ResponseEntity.ok("您的衣物已开始清洗"); // 与“点击洗衣”对应
                    case "washing":
                        order.setStatus("ready_for_pickup");
                        orderService.updateMerchantOrder(order);
                        return ResponseEntity.ok("请前往取衣"); // 与“结束洗衣”对应
                    default:
                        return ResponseEntity.badRequest().body("无效的订单状态");
                }
            } else if ("washing_full_service".equals(serviceType)) {
                switch (status) {
                    case "in_progress":
                        order.setStatus("picked_up");
                        orderService.updateMerchantOrder(order);
                        return ResponseEntity.ok("商家取衣成功"); // 与“点击取衣”对应
                    case "picked_up":
                        order.setStatus("washing");
                        orderService.updateMerchantOrder(order);
                        return ResponseEntity.ok("您的衣物已开始清洗"); // 与“点击洗衣”对应
                    case "washing":
                        order.setStatus("delivering");
                        orderService.updateMerchantOrder(order);
                        return ResponseEntity.ok("您的衣物正在飞速回家"); // 与“开始配送”对应
                    case "delivering":
                        order.setStatus("completed");
                        orderService.updateMerchantOrder(order);
                        return ResponseEntity.ok("订单已完成"); // 与“点击送达”对应
                    default:
                        return ResponseEntity.badRequest().body("无效的订单状态");
                }
            } else if ("rental_pickup_only".equals(serviceType)) {
                switch (status) {
                    case "in_progress":
                        order.setStatus("rentalling");
                        orderService.updateMerchantOrder(order);
                        orderService.startRentalCountdown(order.getOrderId(), order.getRentalDuration());
                        return ResponseEntity.ok("订单状态已更新为租借中"); // 与“点击取衣”对应
                    case "returned":
                        order.setStatus("completed");
                        orderService.updateMerchantOrder(order);
                        return ResponseEntity.ok("订单已完成"); // 与“点击完成”对应
                    default:
                        return ResponseEntity.badRequest().body("无效的订单状态");
                }
            } else if ("rental_full_service".equals(serviceType)) {
                switch (status) {
                    case "in_progress":
                        order.setStatus("rentalling");
                        orderService.updateMerchantOrder(order);
                        orderService.startRentalCountdown(order.getOrderId(), order.getRentalDuration());
                        return ResponseEntity.ok("订单状态已更新为租借中"); // 与“点击取衣”对应
                    case "to_be_returned":
                        order.setStatus("delivering");
                        orderService.updateMerchantOrder(order);
                        return ResponseEntity.ok("订单状态已更新为送件中"); // 与“点击配送”对应
                    case "delivering":
                        order.setStatus("returned");
                        orderService.updateMerchantOrder(order);
                        return ResponseEntity.ok("订单状态已更新为送已归还"); // 与“点击到达”对应
                    case "returned":
                        order.setStatus("completed");
                        orderService.updateMerchantOrder(order);
                        return ResponseEntity.ok("订单已完成"); // 与“点击完成”对应
                    default:
                        return ResponseEntity.badRequest().body("无效的订单状态");
                }
            }

            return ResponseEntity.badRequest().body("无效的服务类型");
        } catch (Exception e) {
            return ResponseEntity.status(500).body("取衣失败: " + e.getMessage());
        }
    }

    @ApiOperation(value = "获取订单详情", notes = "根据订单ID、用户ID和订单类型获取订单详情")
    @GetMapping("/details")
    public ResponseEntity<?> getOrderDetails(
            @RequestParam Integer orderId,
            @RequestParam Integer userId,
            @RequestParam String orderType) {  // 新增参数
        try {
            OrderDetailsResponse orderDetails = orderService.getOrderDetails(orderId, userId, orderType);
            if (orderDetails == null) {
                return ResponseEntity.badRequest().body("订单未找到或无权限查看该订单");
            }
            return ResponseEntity.ok(orderDetails);
        } catch (Exception e) {
            return ResponseEntity.status(500).body("获取订单详情失败: " + e.getMessage());
        }
    }

    @ApiOperation(value = "创建商家订单", notes = "创建商家订单并生成支付记录")
    @PostMapping("/merchant/create")
    public ResponseEntity<?> createMerchantOrder(@RequestBody OrderRequest request) {
        if (request.getUserId() == null) {
            return ResponseEntity.badRequest().body("用户ID不能为空");
        }
        if (request.getPaymentMethod() == null || request.getPaymentMethod().isEmpty()) {
            return ResponseEntity.badRequest().body("支付方式不能为空");
        }
        try {
            // 创建订单和支付记录
            Order order = orderService.createOrderAndPayment(request);

            // 构建统一响应对象
            OrderResponse orderResponse = new OrderResponse();
            orderResponse.setOrderId(order.getOrderId());
            orderResponse.setUserId(request.getUserId());
            orderResponse.setOrderAmount(order.getOrderAmount().doubleValue());
            orderResponse.setPaymentMethod(request.getPaymentMethod());
            orderResponse.setPaymentStatus("pending");
            orderResponse.setTransactionId("TXN_M_" + order.getOrderId()); // 商家订单前缀
            orderResponse.setOrderType("merchant_service"); // 明确订单类型

            return ResponseEntity.ok(new OrderCreationResponse(
                    "商家订单和支付记录已创建，请完成支付。",
                    orderResponse
            ));
        } catch (Exception e) {
            return ResponseEntity.status(500).body("创建订单失败: " + e.getMessage());
        }
    }

    @ApiOperation(value = "创建租赁订单", notes = "创建租赁订单并生成支付记录")
    @PostMapping("/rental/create")
    public ResponseEntity<?> createRentalOrder(@RequestBody RentalOrderRequest request) {
        if (request.getUserId() == null) {
            return ResponseEntity.badRequest().body("用户ID不能为空");
        }
        if (request.getPaymentMethod() == null || request.getPaymentMethod().isEmpty()) {
            return ResponseEntity.badRequest().body("支付方式不能为空");
        }
        if (request.getRentalId() == null) {
            return ResponseEntity.badRequest().body("租赁ID不能为空");
        }
        if (request.getRentalDuration() == null || request.getRentalDuration().compareTo(BigDecimal.ZERO) <= 0) {
            return ResponseEntity.badRequest().body("租赁时长必须大于0");
        }
        if (request.getServiceType() == null || request.getServiceType().isEmpty()) {
            return ResponseEntity.badRequest().body("服务类型不能为空");
        }

        try {
            // 创建租赁订单
            Order order = orderService.createRentalOrder(request);

            // 创建支付记录（状态为 pending）
            PaymentDTO paymentDTO = new PaymentDTO();
            paymentDTO.setOrderId(order.getOrderId());
            paymentDTO.setUserId(request.getUserId());
            paymentDTO.setOrderType("merchant_service"); // 租赁订单属于商家服务
            paymentDTO.setOrderAmount(order.getOrderAmount());
            paymentDTO.setPaymentMethod(request.getPaymentMethod());
            paymentDTO.setTransactionId("TXN_R_" + order.getOrderId());

            paymentService.createPayment(paymentDTO);

            // 创建响应对象
            OrderResponse orderResponse = new OrderResponse();
            orderResponse.setOrderId(order.getOrderId());
            orderResponse.setUserId(request.getUserId());
            orderResponse.setOrderAmount(order.getOrderAmount().doubleValue());  // 将 BigDecimal 转为 Double
            orderResponse.setPaymentMethod(request.getPaymentMethod());
            orderResponse.setPaymentStatus("pending");  // 支付状态为 pending
            orderResponse.setTransactionId(paymentDTO.getTransactionId());
            orderResponse.setOrderType("merchant_service");

            // 返回订单ID和详细信息
            return ResponseEntity.ok(new OrderCreationResponse(
                    "租赁订单和支付记录已创建，请完成支付。",
                    orderResponse
            ));
        } catch (Exception e) {
            return ResponseEntity.status(500).body("创建租赁订单失败: " + e.getMessage());
        }
    }
    @ApiOperation(value = "获取用户的自助服务订单列表", notes = "根据用户ID获取自助服务订单列表")
    @GetMapping("/self-service/list")
    public ResponseEntity<?> getSelfServiceOrdersByUserId(@RequestParam Integer userId) {
        try {
            List<Order> orders = orderService.getSelfServiceOrdersByUserId(userId);
            if (orders.isEmpty()) {
                return ResponseEntity.ok("未找到该用户的自助服务订单");
            }
            return ResponseEntity.ok(orders);
        } catch (Exception e) {
            return ResponseEntity.status(500).body("获取自助服务订单列表失败: " + e.getMessage());
        }
    }

    @ApiOperation(value = "获取用户的商家服务订单列表", notes = "根据用户ID获取商家服务订单列表")
    @GetMapping("/merchant/list")
    public ResponseEntity<?> getMerchantOrdersByUserId(@RequestParam Integer userId) {
        try {
            List<Order> orders = orderService.getMerchantOrdersByUserId(userId);
            if (orders.isEmpty()) {
                return ResponseEntity.ok("未找到该用户的商家服务订单");
            }
            return ResponseEntity.ok(orders);
        } catch (Exception e) {
            return ResponseEntity.status(500).body("获取商家服务订单列表失败: " + e.getMessage());
        }
    }
}
